package com.neu.util;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * 创建retrofit
 */
public class RetrofitUtil {

    public static String BASE_URL="http://124.93.196.45:10001";
    public static RetrofitUtil retrofitManager=null;

    private Retrofit retrofit;

    public static String token="";

    public  RetrofitUtil(){
        createRetrofit();
    }

    private void createRetrofit() {
        OkHttpClient okHttpClient=new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request.Builder builder=chain.request().newBuilder();
                        Request request=builder.addHeader("Authorization",token).build();
                        return chain.proceed(request);
                    }
                }).build();
        retrofit=new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    /**
     * 单例模式，生成唯一实例
     * @return
     */
    public static RetrofitUtil getInstance() {
        if(retrofitManager == null) {
            synchronized(RetrofitUtil.class) {
                if(retrofitManager == null) {
                    retrofitManager = new RetrofitUtil();
                }
            }
        }
        return retrofitManager;
    }

    public <T> T create(Class<T> service){
        return retrofit.create(service);
    }
}
